import { ADD, DECREASE, CLEAR } from '../constants.jsx'

export default function reducer(state = [], action) {
    let { type, payload } = action;
    if (type === ADD) {
        if (state.some(item => item.title === payload.title)) {
            state.forEach(item => {
                if (item.title === payload.title) {
                    item.num++;
                }
            })
        } else {
            state.push({ ...payload, num: 1 })
        }
        return state;
    } else if (type === DECREASE) {
        if (state.some(item => item.title === payload.title)) {
            state.forEach(item => {
                if (item.title === payload.title) {
                    item.num--;
                }
            })
        }
        state = state.filter(item => item.num > 0)
        return state;
    } else if (type === CLEAR) {
        return [];
    }
    return state;
}